package frame;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.menhoo.menhoolibrary.R;
import com.example.menhoo.toollibrary.common.assist.IMEHelper;
import com.example.menhoo.toollibrary.common.assist.Network;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.util.LogUtils;
import com.lsjwzh.loadingeverywhere.GenericStatusLayout;
import com.rey.material.widget.ProgressView;

import java.util.ArrayList;
import java.util.List;

import application.UIApplication;
import interfaces.IReturnObject;
import receiver.NetStateReceiver;

/**
 * Created by yanglei on 15/9/17.
 */
public abstract class UIFragment extends Fragment {

    /**
     * http请求缓存,多长时间返回相同结果
     */
    private long Http_CacheTime = 5000;
    /**
     * http请求之后多长时间超时
     */
    private int Http_Timeout = UIApplication.NetWorkTimeOut;
    private long loadingHideTime = 700;
    public Context context;
    public int viewLayoutID;
    public View rootView;
    public LinearLayout minaLinearLayout;
    public LayoutInflater inflater;

    private Handler handler = new Handler();
    //private DbUtils db;
    private BitmapUtils bitmapLoader;
    private BitmapUtils iconLoader;
    private GenericStatusLayout genericStatusLayout;
    private GenericStatusLayout.ILayerCreator layerCreator;
    private View loadingView;
    private View emptyView;
    private View errorView;
    private AppBarLayout mToolbarContainer;
    /**
     * 错误页面,点击重试时候的回调函数
     */
    private IReturnObject<String> errorViewCall = null;

    private HttpUtils http = new HttpUtils(Http_Timeout);
    private List<HttpHandler> httpHandlerList = new ArrayList();

    //ui
    private LinearLayout frame_ui_context;
    private RelativeLayout frame_ui_title;
    private LinearLayout frame_ui_layout_custom_cnx;
    private ImageView frame_ui_btn_back;
    private TextView frame_ui_tv_title_text;

    private int loadingViewResID = R.layout.frame_ui_loading;
    private int emptyViewResID = R.layout.frame_ui_empty;
    private int errorViewResID = R.layout.frame_ui_error;
    private ProgressDialog progressBar;

    public void setLoadingView(int resID) {
        loadingViewResID = resID;
    }

    public View getLoadingView() {
        return loadingView;
    }

    public abstract boolean onBackPressed();

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            //销毁正在请求的网络资源
            //取消所有的url请求
            if (httpHandlerList != null)
                for (HttpHandler httpHandler : httpHandlerList) {
                    if (httpHandler != null) {
                        httpHandler.cancel();
                    }
                }
            httpHandlerList.removeAll(httpHandlerList);
            httpHandlerList = null;
        } catch (Exception e) {
        }

    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        if (rootView == null) {
            this.inflater = inflater;
            context = inflater.getContext().getApplicationContext();
            rootView = inflater.inflate(R.layout.frame_fragment_ui, null);
            minaLinearLayout = (LinearLayout) rootView.findViewById(R.id.frame_ui_context);
            mToolbarContainer = (AppBarLayout) rootView.findViewById(R.id.mToolbarContainer);
            try {
                View.inflate(context, viewLayoutID, minaLinearLayout);
            } catch (Exception e) {
                LogUtils.e(e.getMessage() + "");
            }
            //db = DbUtils.create(context);
            http.configCurrentHttpCacheExpiry(Http_CacheTime);
            http.configDefaultHttpCacheExpiry(Http_CacheTime);
            bitmapLoader = initBitmapUtils(UIApplication.getAppCachePath(context));
            iconLoader = initBitmapUtils(UIApplication.getAppIconCachePath(context));
            //实例化
            frame_ui_context = (LinearLayout) rootView.findViewById(R.id.frame_ui_context);
            frame_ui_title = (RelativeLayout) rootView.findViewById(R.id.frame_ui_title);
            frame_ui_layout_custom_cnx = (LinearLayout) rootView.findViewById(R.id.frame_ui_layout_custom_cnx);
            frame_ui_btn_back = rootView.findViewById(R.id.frame_ui_btn_back);
            frame_ui_tv_title_text = (TextView) rootView.findViewById(R.id.frame_ui_tv_title_text);
            //onclick
            frame_ui_btn_back.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    getActivity().onBackPressed();
                    onBackPressed();
                }
            });

            ViewUtils.inject(this, rootView);
            initGenericStatusLayout();
            init();
        }
        // 缓存的rootView需要判断是否已经被加过parent，如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }

        return rootView;

    }

    /**
     * 初始化图片载入器
     *
     * @param cachePath 缓存文件的物理位置
     * @return
     */
    private BitmapUtils initBitmapUtils(String cachePath) {
        BitmapUtils bitmapUtils = new BitmapUtils(context, cachePath);
        return bitmapUtils;
    }


    /**
     * 显示内容(除了title) 淡出
     */
    public void showContent() {
        minaLinearLayout.setVisibility(View.VISIBLE);
        minaLinearLayout.startAnimation(UIApplication.getAnimationSet());

    }

    /**
     * 隐藏内容(除了title)
     */
    public void hideContent() {
        minaLinearLayout.setVisibility(View.GONE);
    }

    /**
     * 返回异步图片载入器(普通图片)缓存周期短,默认一天
     *
     * @return
     */
    public BitmapUtils getBitmapLoader() {
        return bitmapLoader;
    }

    /**
     * 返回异步图片载入器(ICON)缓存周期很长,默认一年
     *
     * @return
     */
    public BitmapUtils getIconLoader() {
        return iconLoader;
    }

    public void setContextView(int layout) {
        viewLayoutID = layout;
    }

    /**
     * 注入标题导航栏右侧的自定义布局
     *
     * @param layoutResID
     */
    public void setCustomRightButton(int layoutResID) {
        try {
            View.inflate(context, layoutResID, frame_ui_layout_custom_cnx);
        } catch (Exception e) {
            LogUtils.e(e.getMessage() + "");
        }
    }

    /**
     * 是否显示标题导航栏,默认显示
     *
     * @param isShow true显示  false隐藏
     */
    public void setTitleDisplay(boolean isShow) {
        if (isShow) {
            frame_ui_title.setVisibility(View.VISIBLE);
        } else {
            frame_ui_title.setVisibility(View.GONE);
            if (Build.VERSION.SDK_INT >= 21)
                mToolbarContainer.setElevation(0.0f);
        }

    }

    /**
     * 是否显示返回按钮
     *
     * @param isShow
     */
    public void setBtnBackDisplay(boolean isShow) {
        if (isShow) {
            frame_ui_btn_back.setVisibility(View.VISIBLE);
        } else {
            frame_ui_btn_back.setVisibility(View.INVISIBLE);
        }
    }

    public void setTitle(CharSequence title) {
        frame_ui_tv_title_text.setText(title);
    }

    public void setTitle(int titleId) {
        frame_ui_tv_title_text.setText(getString(titleId));
    }

    /**
     * 初始化请放到这里进行
     */
    public void init() {
    }

    public View getRootView() {
        return rootView;
    }

    /**
     * 得到数据库操作对象
     *
     * @return
     */
    public DbUtils getDB() {
        //return db;
        return UIApplication.getDB();
    }

    /**
     * 初始化遮罩层
     */
    public void initGenericStatusLayout() {
        genericStatusLayout = new GenericStatusLayout(context);
        layerCreator = new GenericStatusLayout.ILayerCreator() {
            @Override
            public View createLoadingLayer() {
                loadingView = getLayoutInflater().inflate(loadingViewResID, null);
                loadingView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        return;
                    }
                });
                return loadingView;
            }

            @Override
            public View createEmptyLayer() {
                emptyView = getLayoutInflater().inflate(emptyViewResID, null);
                return emptyView;
            }

            @Override
            public View createErrorLayer() {
                errorView = inflater.inflate(errorViewResID, null);
                if (errorViewCall != null) {
                    errorView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (errorViewCall != null) {
                                errorViewCall.returnResult("");
                            }
                        }
                    });
                }

                return errorView;
            }
        };
        genericStatusLayout.setLayerCreator(layerCreator);
        genericStatusLayout.attachTo(minaLinearLayout);
    }

    public void showLoading() {
        handler.removeCallbacks(hideRun);
        hideError();
        hideEmpty();
        //隐藏软键盘
        IMEHelper.hideIME(getActivity(), true);

        genericStatusLayout.showLoading();
        if (loadingView != null) {
            ProgressView pv_linear_colors = (ProgressView) loadingView.findViewById(R.id.progress_pv_linear_colors);
            pv_linear_colors.start();
        }
    }

    public void hideLoading() {
        if (loadingView != null) {
            ProgressView pv_linear_colors = (ProgressView) loadingView.findViewById(R.id.progress_pv_linear_colors);
            pv_linear_colors.stop();
        }
        genericStatusLayout.hideLoading();
    }

    public void showEmpty() {
        hideAll();
        genericStatusLayout.showEmpty();
    }

    public void hideEmpty() {
        genericStatusLayout.hideEmpty();
    }

    public void showError(IReturnObject<String> iReturnObject) {
        hideAll();
        errorViewCall = iReturnObject;
        genericStatusLayout.showError();
    }

    public void hideError() {
        genericStatusLayout.hideError();
    }


    Runnable hideRun = new Runnable() {
        @Override
        public void run() {
            hideAll();
        }
    };

    /**
     * 延迟隐藏所有的遮罩层 loading empty error
     *
     * @param delayMillis 延迟隐藏 时间
     */
    public void hideAll(long delayMillis) {
        handler.postDelayed(hideRun, delayMillis);
    }

    /**
     * 隐藏所有的遮罩层 loading empty error
     */
    public void hideAll() {
        handler.removeCallbacks(hideRun);
        hideError();
        hideEmpty();
        hideLoading();
        //隐藏软键盘
        IMEHelper.hideIME(getActivity(), true);
    }


    private void httpHelp(final HttpMethod GetOrPost, final String url, final RequestParams params, final IReturnObject<String> returnObj) {
        httpHelp(GetOrPost, url, params, new RequestCallBack<String>() {
            @Override
            public void onStart() {

            }

            @Override
            public void onLoading(long total, long current, boolean isUploading) {

            }

            @Override
            public void onCancelled() {
                LogUtils.d("url:" + url + ":请求已经取消");
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                LogUtils.d(responseInfo.result + "");
                if (returnObj != null)
                    returnObj.returnResult(responseInfo.result);
                hideAll(loadingHideTime);
            }

            @Override
            public void onFailure(HttpException e, String s) {
                showError(new IReturnObject<String>() {
                    @Override
                    public void returnResult(String result) {
                        httpHelp(GetOrPost, url, params, returnObj);
                    }
                });
                if (returnObj != null)
                    returnObj.returnResult(null);

                LogUtils.e(s + "");
            }
        });
    }

    /**
     * http请求
     *
     * @param GetOrPost get请求 还是 post请求
     * @param url       url地址
     * @param params    要传递的url参数(键值对)
     * @param callBack  当中有 start loading success 和 failure相关回调函数
     */
    public void httpHelp(HttpMethod GetOrPost, String url, RequestParams params, RequestCallBack callBack) {
        httpHelp(GetOrPost, url, params, callBack, true);
    }

    /**
     * http请求
     *
     * @param GetOrPost get请求 还是 post请求
     * @param url       url地址
     * @param params    要传递的url参数(键值对)
     * @param callBack  当中有 start loading success 和 failure相关回调函数
     */
    public void httpHelp(HttpMethod GetOrPost, String url, RequestParams params, RequestCallBack callBack, boolean isShowLoading) {
        if (isShowLoading) {
            showLoading();
        }
        HttpSend(GetOrPost, url, params, callBack);
    }

    /**
     * http请求(最后一级)
     *
     * @param GetOrPost get请求 还是 post请求
     * @param url       url地址
     * @param params    要传递的url参数(键值对)
     * @param callBack  当中有 start loading success 和 failure相关回调函数
     */
    public void HttpSend(final HttpMethod GetOrPost, final String url, final RequestParams params, final RequestCallBack callBack) {
        //检查一下网络状态
        Network.isNetworkAvailable(context, url, new com.example.menhoo.toollibrary.android.async.IReturnObject<Boolean>() {
            @Override
            public void returnResult(Boolean isNetwork) {
                if (isNetwork) {
                    Intent it = new Intent();// 创建Intent对象
                    it.setAction(NetStateReceiver.Action);
                    it.putExtra("isNetworkAvailable", true);
                    it.putExtra("message", getString(R.string.available_network_title));
                    context.sendBroadcast(it);

                    HttpHandler handle = http.send(GetOrPost, url, params, callBack);
                    httpHandlerList.add(handle);
                } else {
                    String message = getString(R.string.no_conn_server);

                    Intent it = new Intent();// 创建Intent对象
                    it.setAction(NetStateReceiver.Action);
                    it.putExtra("isNetworkAvailable", false);
                    it.putExtra("message", message);
                    context.sendBroadcast(it);

                    //MessageUtil.showShortToast(UIActivity.this, "无网络");
                    callBack.onFailure(new HttpException(message), message);
                    //hideAll(loadingHideTime);
                }
            }
        });

    }

    /**
     * http请求
     *
     * @param GetOrPost get请求 还是 post请求
     * @param url       url地址
     * @param callBack  当中有 start loading success 和 failure相关回调函数
     */
    public void httpHelp(HttpMethod GetOrPost, String url, RequestCallBack callBack) {
        httpHelp(GetOrPost, url, null, callBack);
    }

    /**
     * 可以传递参数的Get Http请求
     *
     * @param url       url地址
     * @param params    要传递的url参数(键值对)
     * @param returnObj 成功之后返回的结果字符串
     */
    public void httpGet(String url, RequestParams params, IReturnObject<String> returnObj) {
        httpHelp(HttpMethod.GET, url, params, returnObj);
    }

    /**
     * Get Http请求
     *
     * @param url       url地址
     * @param returnObj 成功之后返回的结果字符串
     */
    public void httpGet(String url, IReturnObject<String> returnObj) {
        httpGet(url, null, returnObj);
    }

    /**
     * 可以传递参数的Post Http请求
     *
     * @param url       url地址
     * @param params    要传递的url参数(键值对)
     * @param returnObj 成功之后返回的结果字符串
     */
    public void httpPost(String url, RequestParams params, IReturnObject<String> returnObj) {
        httpHelp(HttpMethod.POST, url, params, returnObj);
    }

    /**
     * Post Http请求
     *
     * @param url       url地址
     * @param returnObj 成功之后返回的结果字符串
     */
    public void httpPost(String url, IReturnObject<String> returnObj) {
        httpPost(url, null, returnObj);
    }


}
